﻿using UFIDA.U9.MO.Complete;
using UFIDA.U9.SM.Ship;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;
using UFIDA.U9.MO.Enums;
using UFIDA.U9.MO.MO;
using System.Collections.Generic;
using UFSoft.UBF.Security;
using System.Reflection.Emit;
using UFIDA.U9.SM.DealerSO;
using System;
using UFSoft.UBF.Util.DataAccess;

namespace UFIDA.U9.Cust.LS.PlugBE

{
    /// <summary>
    /// 金汇能
    /// 完工报告
    /// 1.生产订单新增字段“收益率”，等于生产订单完工数量/生产订单备料行1、2开头物料已发放数量合计。
    /// 2.生产订单完工数量更新一次，收率计算一次。
    /// 3.增加控制，当生产订单收率超过110%，系统进行报错且不允许完工报告保存。
    /// 4.生产订单收率为自定义段3
    /// </summary>
    class JHNCompleteSLExtend : IEventSubscriber
    {
        //配置XX.sub.xml文件放置到portal/bin下，dll文件放置到portal/ApplicationServer/Libs下
        public void Notify(params object[] args)
        {
            if (args != null && args.Length != 0 && args[0] is EntityEvent)
            {
                BusinessEntity.EntityKey key = ((EntityEvent)args[0]).EntityKey;
                CompleteRpt complete = key.GetEntity() as CompleteRpt;//完工报告
                if (complete == null)
                    return;
                MO.MO.MO mo = MO.MO.MO.Finder.Find($"DocNo='{complete.MO.DocNo}'");
                decimal qtysum=0;
                foreach (var item in mo.MOPickLists)
                {
                    if (item.ItemCode.StartsWith("1") || item.ItemCode.StartsWith("2"))
                    {
                        qtysum += item.IssuedQty;
                    }                  
                }
                if (qtysum > 0) { 
                decimal sl= (mo.ProductQty + complete.CompleteQty) / qtysum;
                
                if ((complete.DocState == UFIDA.U9.MO.Enums.CompleteRptStateEnum.Approved
                    && complete.OriginalData.DocState == UFIDA.U9.MO.Enums.CompleteRptStateEnum.Approving))
                {
                    if (sl * 100 > 110)
                        throw new Exception($"对应生产订单:[{mo.DocNo}]的收益率超过110%,请检查!");
                     //清空私有字段
                    using(ISession session = Session.Open())
                    {
                        mo.DescFlexField.PrivateDescSeg3 = sl.ToString();
                            //mo.DescFlexField.PrivateDescSeg6 = sl.ToString();
                            session.Commit();
                    }
                }
                }
            }
        } 

    }
}
